package com.simple.mq.common.config;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 项目: simple-mq
 *
 * 功能描述: 线程池管理
 *
 * @author: WuChengXing
 *
 * @create: 2023-08-18 17:19
 **/
public class SimpleThreadPool {

    private static final Integer CORE_THREAD_NUM = 5;

    private static final Integer MAX_THREAD_NUM = 10;

    /**
     * 空闲线程回收时间
     */
    private static final Integer THREAD_CYCLE_TIME = 60;

    private static final ThreadFactory THREAD_FACTORY = new ThreadFactory() {
        private final ThreadFactory defaultFactory = Executors.defaultThreadFactory();
        private final AtomicInteger threadNumber = new AtomicInteger(1);

        @Override
        public Thread newThread(Runnable r) {
            Thread thread = this.defaultFactory.newThread(r);
            if (!thread.isDaemon()) {
                thread.setDaemon(true);
            }

            thread.setName("SimpleMQ-" + this.threadNumber.getAndIncrement());
            return thread;
        }
    };


    private static ThreadPoolExecutor pluginThreadPool() {
        return new ThreadPoolExecutor(CORE_THREAD_NUM, MAX_THREAD_NUM, THREAD_CYCLE_TIME, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10), THREAD_FACTORY);
    }

    public static ThreadPoolExecutor INSTANCE = SimpleThreadPool.pluginThreadPool();
}
